import React, { useEffect, useState } from 'react'
import NetworkHeader from '@/pages/Netdisk/NetworkHeader'
import { Table, Tag, Popconfirm, Modal, Form, Input, Space, Button } from 'antd';
import http from '@/utils/http'
import type { ColumnsType } from 'antd/es/table';

interface baseComonBoxViewProps {
  title?: string;
  isAddBtn?: boolean,
  columns: any[],
  paramsObj: {
    url: string;
    method: "POST" | "GET",
    data: any
  },
  listName: string
}

interface DataType {
  [key: string]: string
}

const useTable = (init: any) => {
  const confirm = (record: any) => {
    // 删除操作
    console.log(record)
    const { _id } = record;
    http({
      url: "/banner/deleteBannerList",
      method: "POST",
      data: { _id }
    }).then(res => {
      init()
    })
  };

  const cancel = (record: any) => {
    console.log(record)
  };
  return [confirm, cancel]
}


const CommonBoxView: React.FC<baseComonBoxViewProps> = ({
  title,
  isAddBtn,
  columns,
  paramsObj,
  listName
}) => {
  const [list, setList] = useState([]);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [form] = Form.useForm();
  const [selectItem, setSelectItem] = useState<DataType>({});
  const [eidtType, setEditType] = useState('')

  // 初始化
  useEffect(() => { init() }, [])

  useEffect(() => { form.resetFields() }, [isModalOpen])

  // 请求接口
  const init = () => {
    console.log(paramsObj, 'paramsObj')
    http(paramsObj).then(res => {
      if (res) {
        setList(res[listName])
      }
    })
  }

  const [confirm, cancel] = useTable(init);

  const layout = { labelCol: { span: 5 }, wrapperCol: { span: 16 } };

  const handleEdit = (record: DataType) => {
    setSelectItem(record)
    setIsModalOpen(true)
  }

  const handleOk = () => {
    const obj = eidtType == "add" ? { action: "add" } : { _id: selectItem?._id, action: "edit" }
    form.validateFields().then(values => {
      http({
        url: "/banner/updateBannerList",
        method: "POST",
        data: { ...obj, ...values }
      }).then((res: any) => {
        init();
        setIsModalOpen(false)
        setEditType("")
      })
    })
  }

  const handleCancel = () => {
    form.resetFields()
    setSelectItem({})
    setIsModalOpen(false)
    setEditType("")
  }

  const handleClickAdd = () => {
    setIsModalOpen(true)
    setEditType("add")
  }

  const compareColumns: ColumnsType<DataType> = [...columns, {
    title: '列表操作',
    dataIndex: 'options',
    width: "300px",
    key: 'options',
    render: (text, record) => (
      <>
        <Popconfirm
          title="确定要删除该图片吗,此处删除直接清库？"
          onConfirm={() => confirm(record) as any}
          onCancel={() => cancel(record) as any}
          okText="是"
          cancelText="否"
        >
          <Tag className='tag-style' color='red'>删除数据</Tag>
        </Popconfirm>
        <Tag className='tag-style' color='blue' onClick={() => handleEdit(record)}>编辑数据</Tag>
      </>
    ),
  }]

  return (
    <>
      <NetworkHeader>{title}</NetworkHeader>
      <div style={{ display: 'flex', justifyContent: "left" }}>
        {
          !isAddBtn &&
          <Space>
            <Button type='primary' onClick={() => handleClickAdd()}>新增轮播图片</Button>
          </Space>
        }
      </div>
      <Table
        columns={compareColumns}
        dataSource={list}
        rowKey={(record) => record?._id}
      />
      <Modal title="用户编辑" visible={isModalOpen} onOk={handleOk} onCancel={handleCancel}>
        <Form
          {...layout}
          form={form}
          initialValues={selectItem}
          className='register-box'>
          <Form.Item
            name="imgUrl"
            label="图片地址"
            rules={[{ required: true, message: "请输入图片地址" }]}
          >
            <Input placeholder={"请输入图片地址"} type="text" id={"imgUrl"} className="inputheight" />
          </Form.Item>
          <Form.Item
            name="jumpUrl"
            label="跳转地址"
            rules={[{ required: true, message: "请输入跳转地址" }]}
          >
            <Input placeholder={"请输入跳转地址"} type="jumpUrl" id={"jumpUrl"} className="inputheight" />
          </Form.Item>
        </Form>
      </Modal >
    </>
  )
}

export default CommonBoxView